import auto_log
import auto_vm
import auto_utility

import os
import shutil

ID_AUTO_READ_SETTING = "auto_read_setting"
ID_MSI_GET_SERIAL = "msi_get_serial"
ID_PREPARE = "prepare"
ID_RUN_VMX_TEST = "run_vmx_test"

AUTOTEST_UTILITIES = "Autotest_Utilities"
AUTOTEST_SCRIPTS = "Autotest_Scripts"
AUTOTEST_FILES_LIST = "Autotest_Files"
AUTOTEST_LOGS = "Autotest_Logs"

AUTOTEST_SERIAL_XML = "msi_serial.xml"

PYTHON_LIB = ["Python31\\Lib"]

def auto_read_setting(path, setting, log = auto_log.LOG_TO_STDOUT):
    id = ID_AUTO_READ_SETTING
    #--------------------------------------------
    #read data from file
    try:
        file = open(path, "r")
        data = file.read()
        file.close()
    except:
        message = "Can't read " + path
        auto_log.write_result(log, message, auto_log.STATUS_ERROR, id)
        result = {"err": message, "res": ""}
        return result
    #--------------------------------------------
    #creating tags
    try:
        start = "<" + setting + ">"
        end = "</" + setting + ">"
    except:
        message = "Incorrect parameter - setting"
        auto_log.write_result(log, message, auto_log.STATUS_ERROR, id)
        result = {"err": message, "res": ""}
        return result
    #--------------------------------------------
    #get value
    try:
        value = (data.split(start)[1]).split(end)[0]
    except:
        message = "Can't read parameter " + setting + " from " + path
        auto_log.write_result(log, message, auto_log.STATUS_ERROR, id)
        result = {"err": message, "res": ""}
        return result
    #--------------------------------------------
    result = {"err": 0, "res": value}
    return result
#-------------------------------------------------------------------------------

def msi_get_serial(msi, serial_info, log = auto_log.LOG_TO_STDOUT):
    id = ID_MSI_GET_SERIAL
    #----------------------------------------------------------------------
    #check paths
    result = auto_utility.check_paths_exists([serial_info])
    if result != 0:
        message = result
        auto_log.write_result(log, message, auto_log.STATUS_ERROR, id)
        result = {"err": message, "res": []}
        return result
    #----------------------------------------------------------------------
    #get msi name
    try:
        msi_name = msi.split("\\")[-1]
    except:
        msi_name = msi
    #----------------------------------------------------------------------
    #read file
    try:
        file = open(serial_info, "r")
        data = file.read()
        file.close()
    except:
        message = "Can't read " + serial_info
        auto_log.write_result(log, message, auto_log.STATUS_ERROR, id)
        result = {"err": message, "res": []}
        return result
    #----------------------------------------------------------------------
    #split file by records
    try:
        records = data.split("<product>")[1:]
    except:
        message = "Can't split " + serial_info + " to product records"
        auto_log.write_result(log, message, auto_log.STATUS_ERROR, id)
        result = {"err": message, "res": []}
        return result
    #----------------------------------------------------------------------
    #get info from each record
    try:
        for item in records:
            product = item.split("<msi>")[1].split("</msi>")[0]
            key = item.split("<product_key>")[1].split("</product_key>")[0]
            serial = item.split("<serial>")[1].split("</serial>")[0]
            if msi_name.upper().startswith(product.upper()):
                result = {"err": 0, "res": [key, serial]}
                return result
    except:
        message = "Can't get info from record. Correct your serial info file format!"
        auto_log.write_result(log, message, auto_log.STATUS_ERROR, id)
        result = {"err": message, "res": []}
        return result
    #----------------------------------------------------------------------
    #no records about msi_name found
    result = {"err": 0, "res": []}
    return result
#----------------------------------------------------------------------

## <b>Description:</b> The function prepares defined volume for autotesting.
#  The function prepares defined volume for autotesting. The function copies python modules (<i>modules</i>), utilities (<i>utilities</i>), 
# script (<i>script</i>) to defined volume (<i>letter</i>) and creates run.bat on it.
#  The run.bat file content consists of <i>script</i> file call with parameters defined in <i>parameters</i> string. 
#  <br><br>The script file itself is copied to auto_utility.AUTOTEST_RUN directory on selected volume <i>letter</i>, 
#  in other words letter + "\\" + auto_utility.AUTOTEST_RUN
#  <br>The utilities are copied to auto_utility.AUTOTEST_UTILITIES directory on selected volume <i>letter</i>, 
#  in other words letter + "\\" + auto_utility.AUTOTEST_UTILITIES
#  <br>The python modules are copied to python lib directory on selected volume <i>letter</i>, 
#  in other words letter + "\\" + auto_utility.PYTHON_LIB_FOLDER
#  <br>Also the function creates empty folder for logging: letter + "\\" + auto_utility.AUTOTEST_LOGS
#  <br><br>In case of success the function returns integer value = 0.
#  <br>In case of error the function returns string value with error description.
#  @param letter
#  string value = selected volume letter (example: "y:")
#  @param modules
#  string value = path to python modules (example: "c:\\my_modules")
#  @param utilities
#  string value = path to utilities (example: "c:\\utilities")
#  @param script
#  string value = path to script (example: "c:\\my_scripts\\test.py")
#  @param parameters
#  string value = parameters line (example: "c:\\scripts\\layout.ini 3") 
#  @param log
#  string value = path to file for logging. Default value auto_log.LOG_TO_STDOUT - log to stdout. 
#  Also you can use auto_log.LOG_TO_NONE to disable logging.
#  
## <b>Example:</b>
#  <br>@code
#from auto_utility import prepare
#
#letter = "y:"
#modules = "c:\\my_modules"
#utilities = "c:\\utilities"
#script = "c:\\my_scripts\\test.py"
#parameters = "c:\\scripts\\layout.ini 3"
#
#result = prepare(letter, modules, utilities, script, parameters)
#if result != 0:
#    print("Error = " + result)
#else:
#    print("Ok - prepare completed successfully.")
#@endcode
def prepare(letter, modules, utilities, scripts, files_list, main, parameters, log = auto_log.LOG_TO_STDOUT):
    id = ID_PREPARE
    #----------------------------------------------------------------------
    #check paths
    result = auto_utility.check_paths_exists([letter, modules, utilities, scripts, main] + files_list)
    if result != 0:
        message = result
        auto_log.write_result(log, message, auto_log.STATUS_ERROR, id)
        return message
    #----------------------------------------------------------------------
    #copy python modules
    if modules != "":
        python_lib_folder = ""
        for folder in PYTHON_LIB:
            if (os.path.exists(letter + "\\" + folder)):
                python_lib_folder = folder
                break
        #-------------------------------------------------
        if python_lib_folder == "":
            message = "Can't find python lib folder in " + letter
            auto_log.write_result(log, message, auto_log.STATUS_ERROR, id)
            return message
        #-------------------------------------------------
        result = auto_utility.copy_python_modules(modules, letter + "\\" + python_lib_folder)
        if result != 0:
            message = result
            auto_log.write_result(log, message, auto_log.STATUS_ERROR, id)
            return message
    #----------------------------------------------------------------------
    #copy folder with utilities
    result = auto_utility.copy_folder(utilities, letter + "\\" + AUTOTEST_UTILITIES)
    if result != 0:
        message = result
        auto_log.write_result(log, message, auto_log.STATUS_ERROR, id)
        return message
    #----------------------------------------------------------------------
    #copy folder with scripts
    result = auto_utility.copy_folder(scripts, letter + "\\" + AUTOTEST_SCRIPTS)
    if result != 0:
        message = result
        auto_log.write_result(log, message, auto_log.STATUS_ERROR, id)
        return message
    #----------------------------------------------------------------------
    #copy list of files
    result = auto_utility.copy_files_list(files_list, letter + "\\" + AUTOTEST_FILES_LIST)
    if result != 0:
        message = result
        auto_log.write_result(log, message, auto_log.STATUS_ERROR, id)
        return message
    #----------------------------------------------------------------------
    #create empty folder for logs
    logs_folder = letter + "\\" + AUTOTEST_LOGS
    try:
        if os.path.exists(logs_folder):
            shutil.rmtree(logs_folder)
        os.mkdir(logs_folder)
    except:
        message = "Can't create folder " + logs_folder
        auto_log.write_result(log, message, auto_log.STATUS_ERROR, id)
        return message
    #----------------------------------------------------------------------
    result = auto_utility.create_run_bat(main, parameters, letter)
    if result != 0:
        message = result
        auto_log.write_result(log, message, auto_log.STATUS_ERROR, id)
        return message
    #----------------------------------------------------------------------
    
    return 0
#----------------------------------------------------------------------

def run_vmx_test(vmrun, vmmount, vmx, results, letter, modules, utilities, scripts, files_list, main, parameters, limit, log = auto_log.LOG_TO_STDOUT):
    id = ID_RUN_VMX_TEST
    #----------------------------------------------------------------------
    #check paths
    result = auto_utility.check_paths_exists([vmrun, vmmount, vmx, modules, utilities, scripts, main] + files_list)
    if result != 0:
        message = result
        auto_log.write_result(log, message, auto_log.STATUS_ERROR, id)
        return message
    #----------------------------------------------------------------------
    #mount vmx
    result = auto_vm.vm_mount_windows_vmx(vmmount, letter, vmx)
    if result != 0:
        message = result
        auto_log.write_result(log, message, auto_log.STATUS_ERROR, id)
        return message
    #----------------------------------------------------------------------
    #prepare for testing
    result = prepare(letter, modules, utilities, scripts, files_list, main, parameters, log)
    if result != 0:
        message = result
        auto_log.write_result(log, message, auto_log.STATUS_ERROR, id)
        return message
    #----------------------------------------------------------------------
    auto_vm.vm_unmount(vmmount, letter, log)
    #----------------------------------------------------------------------
    auto_vm.vm_start(vmrun, vmx, log)
    #----------------------------------------------------------------------
    result = auto_vm.vm_wait_and_mount_vmx(vmmount, letter, vmx, limit)
    if result != 0:
        auto_vm.vm_stop(vmrun, vmx, log)
        message = "VMWare works too long!"
        auto_log.write_result(log, message, auto_log.STATUS_ERROR, id)
        return message
    #----------------------------------------------------------------------
    #copy logs
    try:
        auto_utility.copy_folder(letter + "\\" + AUTOTEST_LOGS, results, log)
    except:
        message = "Can not copy " + letter + "\\" + AUTOTEST_LOGS + " to " + results
        auto_log.write_result(log, message, auto_log.STATUS_ERROR, id)
        auto_vm.vm_unmount(vmmount, letter, log)
        return message
    #----------------------------------------------------------------------
    auto_vm.vm_unmount(vmmount, letter, log)
    #----------------------------------------------------------------------
    return 0
#----------------------------------------------------------------------